package cn.wolfcode.web.modules.linkmanvisit.controller;

import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;
import cn.wolfcode.web.modules.linkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.linkman.service.ITbCustLinkmanService;
import cn.wolfcode.web.modules.linkmanvisit.entity.TbVisit;
import cn.wolfcode.web.modules.linkmanvisit.service.ITbVisitService;
import cn.wolfcode.web.modules.log.LogModules;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author MAOWEI
 * @since 2023-08-01
 */
@Controller
@RequestMapping("linkmanvisit")
public class TbVisitController extends BaseController {

    @Autowired
    private ITbVisitService entityService;

    @Autowired
    private ITbCustomerService customerService;

    @Autowired
    private ITbCustLinkmanService custLinkmanService;

    private static final String LogModule = "TbVisit";

    @GetMapping("/list.html")
    public String list() {
        return "visit/linkmanvisit/list";
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('visit:linkmanvisit:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        List<TbCustomer> customerList = customerService.list();
        mv.addObject("custs", customerList);
        List<TbCustLinkman> custLinkmanList = custLinkmanService.list();
        mv.addObject("custlinkmans", custLinkmanList);
        mv.setViewName("visit/linkmanvisit/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('visit:linkmanvisit:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        List<TbCustomer> customerList = customerService.list();
        mv.addObject("custs", customerList);
        List<TbCustLinkman> custLinkmanList = custLinkmanService.list();
        mv.addObject("custlinkmans", custLinkmanList);
        mv.setViewName("visit/linkmanvisit/update");
        TbVisit tbVisit = entityService.getById(id);
        mv.addObject("obj", tbVisit);
        List<TbCustLinkman> list = custLinkmanService.list(new LambdaQueryWrapper<TbCustLinkman>().eq(TbCustLinkman::getCustId, tbVisit.getCustId()));
        mv.addObject("custLinkManList", list);
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('visit:linkmanvisit:list')")
    public ResponseEntity page(LayuiPage layuiPage, String parameterName, Long visitType, String startVisitDate, String endVisitDate) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        LambdaQueryWrapper<TbVisit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .and(visitType != null, q -> {
                    q.eq(TbVisit::getVisitType, visitType);
                })
                .and(StringUtils.isNotBlank(parameterName), query -> {
                    query.like(TbVisit::getVisitReason, parameterName)
                            .or()
                            .like(TbVisit::getContent, parameterName);
                })
                .and(StringUtils.isNotBlank(startVisitDate), query -> {
                    query.ge(TbVisit::getVisitDate, startVisitDate).le(TbVisit::getVisitDate, endVisitDate);
                });

        IPage iPage = entityService.page(page, queryWrapper);
        List<TbVisit> tbVisitList = iPage.getRecords();
        for (TbVisit tbVisit : tbVisitList) {
            tbVisit.setCustName(customerService.getById(tbVisit.getCustId()).getCustomerName());
            tbVisit.setLinkmanName(custLinkmanService.getById(tbVisit.getLinkmanId()).getLinkman());
        }
        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(iPage));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module = LogModule)
    @PreAuthorize("hasAuthority('visit:linkmanvisit:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbVisit entity) {
        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('visit:linkmanvisit:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbVisit entity) {
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('visit:linkmanvisit:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @RequestMapping("listByCustomerId")
    public ResponseEntity<ApiModel> listByCustomerId(String custId) {
        LambdaQueryWrapper<TbCustLinkman> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbCustLinkman::getCustId, custId);
        List<TbCustLinkman> custLinkmanList = custLinkmanService.list(queryWrapper);
        return ResponseEntity.ok(ApiModel.data(custLinkmanList));
    }

}
